# coding=utf-8

import json,urllib2

class Ingress:
	def __init__(self,csrftoken,acsid):
		self.csrftoken = csrftoken
		self.cookie = 'ACSID='+acsid+';csrftoken='+csrftoken
	def submit(self,passcode):
		passcode_url = 'http://www.ingress.com/rpc/dashboard.redeemReward'
		data_json = json.dumps({"passcode":passcode,"method":"dashboard.redeemReward"}) 
		req = urllib2.Request(passcode_url, data=data_json)
		req.add_header('Cookie',self.cookie)
		req.add_header('X-Requested-With','XMLHttpRequest')
		req.add_header('X-CSRFToken',self.csrftoken)
		response=urllib2.urlopen(req)
		content = response.read()
		try:
			ap = json.loads(content)['gameBasket']['playerEntity'][2]['playerPersonal']['ap']
			ap_inc = json.loads(content)['result']['apAward']
			xm_inc = json.loads(content)['result']['xmAward']
			inventoryAward = json.loads(content)['result']['inventoryAward']
			newItems = {}
			for i in range(len(inventoryAward)):
				if len(inventoryAward[i][2]) == 2:
					item = '%s Portal Shield' %inventoryAward[i][2]['modResource']['rarity']
				elif len(inventoryAward[i][2]) == 3:
					item = 'L%i Resonator' %inventoryAward[i][2]['resourceWithLevels']['level']
				else:
					item = 'L%i XMP' %inventoryAward[i][2]['resourceWithLevels']['level']
				if item not in newItems:
					newItems[item] = 0
				newItems[item] += 1
			doc = 'Total: '+ap+'AP; Gained: '+ap_inc+'AP, '+xm_inc+'XM; '
			for item in newItems:
				doc += item+' x '+str(newItems[item])+'; '
		except:
			doc = content
		return doc
		
			
if __name__ == "__main__":
	acsid = ''
	csrftoken=''
	i = 800
	while True:
		i = i-1
		passcode = 'FYD4'+str(i)
		print passcode
		print Ingress(csrftoken,acsid).submit(passcode)
